#include <map>
#include <functional>
#include <numeric>
#include <tr1/memory>

#include <boost/foreach.hpp>

#include "idxutils.h"
#include "query_vector.h"

namespace jsearch
{

struct query_vector::Impl
{
		Impl(std::tr1::shared_ptr<std::vector<std::string> >& svec)
		{
			terms=svec;
		}

		void query_build()
		{
			qfreq.clear();
			std::map<std::string,int> words;

			BOOST_FOREACH(std::string& s,*terms)
			{
				++words[str_tolower(s)];
			}

			int max_freq = 0;
			typedef std::map<std::string,int>::value_type SIV;
			BOOST_FOREACH(SIV& siv, words)
			{
				if (siv.second > max_freq)
					max_freq = siv.second;
			}

			double q=static_cast<double>(max_freq);
			BOOST_FOREACH(SIV& siv, words)
			{
				double p=static_cast<double>(siv.second);
				qfreq[siv.first] = 0.5+0.5*(p/q);
			}
		}

		double get_freq(std::string tm) const
		{
			std::string term = str_tolower(tm);
			std::map<std::string, double>::const_iterator \
				pos = qfreq.find(term);
			if (pos != qfreq.end())
				return pos->second;

			return 0.0;

		}

		std::tr1::shared_ptr<std::vector<std::string> > get_terms()
		{
			return terms;
		}

	private:
		std::tr1::shared_ptr< std::vector<std::string> > terms;
		std::map<std::string, double> qfreq;
};


//=============================================
// member function of query function
//=============================================

query_vector::query_vector(std::tr1::shared_ptr< std::vector<std::string> >& svec)
	:pimpl(new Impl(svec))
{ }

void query_vector::query_build()
{
	pimpl->query_build();
}

double query_vector::get_freq(std::string tm) const
{
	return pimpl->get_freq(tm);
}

std::tr1::shared_ptr< std::vector<std::string> >
query_vector::get_terms()
{
	return pimpl->get_terms();
}

}//end namespace
